# Maintainer: Feng Shu <tumashu@163.com>

_realname=librime
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.11.2
pkgrel=1
pkgdesc="Rime Input Method Engine Library (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://rime.im/'
msys2_repository_url="https://github.com/rime/librime"
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-leveldb"
         "${MINGW_PACKAGE_PREFIX}-opencc"
         "${MINGW_PACKAGE_PREFIX}-yaml-cpp"
         "${MINGW_PACKAGE_PREFIX}-glog")
optdepends=("${MINGW_PACKAGE_PREFIX}-rime-data: Rime schema repository from plum")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-boost"
             "${MINGW_PACKAGE_PREFIX}-marisa")
checkdepends=("${MINGW_PACKAGE_PREFIX}-gtest")
source=("https://github.com/rime/librime/archive/${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-fix-librime-path.patch"
        "002-librime-fix-llvm-rc.patch")
sha256sums=('0a3f507d11aeb137de08e90fd319714533caf210b97223d8a12994db215684b5'
            '8f604a89679cd0fb82716387c4da9a244b69d04d18b39c765aa8eb9d6424ff57'
            'fcddd5b4f817ba4bda81cd428ff8b6962ed8e4124722e1de99875697e354c355')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${_realname}-${pkgver}"
  apply_patch_with_msg \
    001-fix-librime-path.patch \
    002-librime-fix-llvm-rc.patch
}

build() {
  mkdir -p "${srcdir}"/build-${MSYSTEM} && cd "${srcdir}"/build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  export CXXFLAGS="$CXXFLAGS -DNDEBUG -DGLOG_USE_GLOG_EXPORT -DGLOG_USE_GFLAGS"
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    "${_extra_config[@]}" \
    -DBUILD_TEST=OFF \
    "../${_realname}-${pkgver}"

  ${MINGW_PREFIX}/bin/cmake --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/cmake -DBUILD_TEST=ON ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake --build .

  PATH=${PATH}:"${srcdir}/build-${MSYSTEM}/bin" ${MINGW_PREFIX}/bin/ctest .
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .
  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
